package com.xhs.zdl.demo.zxing;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;
import com.xhs.zdl.demo.R;

public class ZXingDemo extends AppCompatActivity {

    private static final int REQUEST_CODE = 1;
    private Button scan;
    private TextView tv_show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zxing_demo);

        ZXingLibrary.initDisplayOpinion(this);

        findView();
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        scan.setOnClickListener(onClickListener);
    }

    /**
     * 拿到控件
     */
    private void findView() {
        scan = (Button) findViewById(R.id.scan);
        tv_show = (TextView) findViewById(R.id.tv_show);
    }

    /**
     * 点击事件
     */
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.scan:
                    scanOnClick();
                    break;
            }
        }
    };

    /**
     * 点击扫描二维码按钮
     */
    private void scanOnClick(){
        Intent intent = new Intent(this, MyScan.class);
        startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * 接收扫描结果
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE){
            //处理扫描结果，在界面上展示
            if (null != data){
                Bundle bundle = data.getExtras();
                if (null == bundle){
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS){
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    scanSuccess(result);
                }else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED){
                    Toast.makeText(this, "解析失败...", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 扫描成功后的逻辑
     * @param result:扫描返回的结果
     */
    private void scanSuccess(String result){
//        tv_show.setText(result);
        Intent intent = new Intent(this, CommitActivity.class);
        intent.putExtra("result", result);
        startActivity(intent);
    }
}
